// 将数组转换为对象，键和值类型由泛型控制
const arrayToObject = <T extends Record<string, unknown>>(arr: T[], keyField: keyof T): Record<string, T> => {
    return arr.reduce(
        (obj, item) => {
            const key = String(item[keyField])
            obj[key] = item
            return obj
        },
        {} as Record<string, T>
    )
}

// 将对象转换为键值对数组
const objectToArray = <T extends Record<string, unknown>>(obj: T): Array<[string, unknown]> => {
    return Object.entries(obj)
}

// 提取对象指定属性的值数组
const objectValuesToArray = <T extends object, K extends keyof T>(obj: T, key: K): T[K][] => {
    return Object.values(obj).map((item) => item[key])
}

// 获取对象第一个键值对
const getFirstKeyValuePair = <T extends Record<string, any>>(obj: T): [keyof T, T[keyof T]] | undefined => {
    const entries = Object.entries(obj)
    return entries.length > 0 ? [entries[0][0], entries[0][1]] : undefined
}

function formatFileSize(bytes: number): string {
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`
    if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(2)} MB`
    return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`
}

export default {
    arrayToObject,
    objectToArray,
    objectValuesToArray,
    getFirstKeyValuePair,
    formatFileSize
}
